package com.gexiao.controller;

import cn.hutool.core.lang.Console;
import cn.hutool.core.util.IdUtil;
import com.gexiao.queue.DeferredQueue;
import com.gexiao.service.DemoService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.concurrent.Callable;

@Controller
public class DemoController {

    private DemoService demoService;

    public DemoController(DemoService demoService) {
        this.demoService = demoService;
    }

    @ResponseBody
    @GetMapping("/hello-world")
    public String helloWorld() throws InterruptedException {
        Console.log("{},耗时：{}", Thread.currentThread(), System.currentTimeMillis());

        doSomeThing();
        return demoService.helloWorld("gexiao:");
    }

    @GetMapping("/success")
    public String success() {
        return "success";
    }

    private void doSomeThing() throws InterruptedException {
        Thread.sleep(3000);
        Console.log("{},耗时：{}", Thread.currentThread(), System.currentTimeMillis());
    }

    /**
     * 异步请求
     *
     * @return
     * @throws InterruptedException
     * @see Callable
     */
    @GetMapping("/async1")
    @ResponseBody
    public Callable<String> asyncHelloWorld() throws InterruptedException {
        Console.log("主线程：{},耗时：{}", Thread.currentThread(), System.currentTimeMillis());

        Callable<String> call = () -> {
            Console.log("副线程：{},耗时：{}", Thread.currentThread(), System.currentTimeMillis());
            Thread.sleep(3000);
            Console.log("副线程：{},耗时：{}", Thread.currentThread(), System.currentTimeMillis());
            return "测试异步调用";
        };
        Console.log("主线程：{},耗时：{}", Thread.currentThread(), System.currentTimeMillis());
        return call;
    }

    /**
     * 异步请求，创建订单
     *
     * @return
     * @throws InterruptedException
     * @see org.springframework.web.context.request.async.DeferredResult
     */
    @GetMapping("/create/order")
    @ResponseBody
    public DeferredResult createOrder() throws InterruptedException {
        DeferredResult deferredResult = new DeferredResult(5000L, "create order fail");
        DeferredQueue.save(deferredResult);
        return deferredResult;
    }

    @GetMapping("/create")
    @ResponseBody
    public String create() throws InterruptedException {
        String order = IdUtil.simpleUUID();
        DeferredResult deferredResult = DeferredQueue.get();
        deferredResult.setResult(order);
        return "order：" + order;
    }
}
